package com.rlz.framemm.proxy;
import java.lang.reflect.Proxy;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created by RLZ
 * on 2021/10/14
 */
public class ProxyFactory {

    @Nullable
    @SuppressWarnings("unchecked")
    public static <T> T create(@NonNull Class<T> clz, @NonNull Class<? extends T> clazz) {
        validateServiceInterface(clz);
        try {
            RealHandler handler = new RealHandler(clazz.newInstance());
            return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, handler);
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
            return null;
        }

    }

    private static void validateServiceInterface(Class<?> clz) {
        if (!clz.isInterface()) {
            throw new IllegalArgumentException("the class must be interfaces.");
        }
    }
}
